#include "RoleManager.h"

RoleManager::RoleManager()
{
	//ctor
}

RoleManager::~RoleManager()
{
	//dtor
}


bool RoleManager::Init(Database& _pDB)
{
	m_pDB = &_pDB;
	return true;
}

bool RoleManager::isExist(int _roleId)
{
	// 如果内存中已经有了
	if(m_DataMap.count(_roleId) > 0)
		return true;

	// 如果数据库中已经有了
	if(m_pDB->IsExistRole(_roleId))
		return true;

	return false;
}

// 成功：返回角色ID -1:插入数据错误 -2:已经存在了
int RoleManager::Create(int _cfgId, string _name, GlobalManager* _pGlobalMgr)
{
	// 如果帐号已经存在
	int newId = _pGlobalMgr->GetValue(eGlobalKey::RoleCount) + 1;
	if(isExist(newId))
	{
		Debug::Error(__func__, " isExist, newId:", newId);
		return -2;
	}

	// 创建一个角色
	tRole newT;
	newT.id = newId;
	newT.cfgId = _cfgId;
	newT.type = 1;
	newT.lv = 0;
	newT.exp = 0;

	newT.hp = 100;
	newT.countryId = 0;
	newT.cityId = 0;
	newT.buildId = 0;
	newT.jobId = 0;

	newT.houseId = 0;
	newT.name = _name;
	newT.desc = "无";

	if( m_pDB->InsertRole(newT) != 0)
	{
		Debug::Error(__func__, " m_pDB InsertRole error, newId:", newId);
		return -1;
	}

	if( !_pGlobalMgr->UpdateValue(eGlobalKey::RoleCount, newId))
	{
		Debug::Error(__func__, " _pGlobalMgr->UpdateValue ret false newId:", newId);
		return -1;
	}

	// 缓存
	Cache(&newT);
	return newId;
}

bool RoleManager::Cache(tRole* _pDB)
{
	if(m_DataMap.count(_pDB->id) > 0)
	{
		Debug::Error(__func__, " Alreay in RoleManager Cache _DB.id:", _pDB->id);
		return false;
	}

	Role Data;
	Data.m_oid = _pDB->id;
	Data.m_cfgId = _pDB->cfgId;
	Data.m_type = _pDB->type;
	Data.m_lv = _pDB->lv;
	Data.m_exp = _pDB->exp;

	Data.m_hp = _pDB->hp;
	Data.m_countryId = _pDB->countryId;
	Data.m_cityId = _pDB->cityId;
	Data.m_buildId = _pDB->buildId;
	Data.m_jobId = _pDB->jobId;

	Data.m_houseId = _pDB->houseId;
	Data.m_name = _pDB->name;
	Data.m_desc = _pDB->desc;

	m_DataMap[Data.m_oid] = Data;
	return true;
}

 Role* RoleManager::Get(int _roleId)
 {
	// 如果内存中已经有了
 	if(m_DataMap.count(_roleId) > 0)
		return &m_DataMap[_roleId];

	// 如果内存没有 则向数据库中查询
    tRole* pDB = m_pDB->SelectRole(_roleId);
    if(pDB == nullptr)
	{
		return nullptr;
	}

	Cache(pDB);
	return &m_DataMap[_roleId];
 }
